<?php
/**
 * Description: 获取已完成的上岸计划历史
 * User: devforma
 * Date: 15/1/7
 * Time: 11:09
 */

require __DIR__ . '/includes/utils.php';

class GetHistoryPlan implements iController {
    
    private $userIdField, $userId;
    
    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $uddb;

        //分页参数校验
        if (!isset($queryArgs['offset']) || filter_var($queryArgs['offset'], FILTER_VALIDATE_INT) === false || $queryArgs['offset'] < 0
            || empty($queryArgs['count']) || filter_var($queryArgs['count'], FILTER_VALIDATE_INT) === false || $queryArgs['count'] < 1) {
            return genOutput(1000);
        }
        
        //用户身份校验
        $u = validateUser($queryArgs); 
        if ($u == 1) { //正式用户
            $this->userIdField = 'user_id';
            $this->userId = $queryArgs['user_id'];
        } elseif ($u == 2) { //游客
            $this->userIdField = 'guest_id';
            $this->userId = $queryArgs['guest_id'];
        } else {
            return genOutput(1000);
        }
        
        //获取任务类型信息
        $taskTypeData = DailyPlanUtils::getMissionMeta();
        
        //获取最近几天完成的任务
        $sql = "SELECT * FROM `{$uddb->recentMissionInfo}` WHERE `{$this->userIdField}`=:user AND `action_type`=1 AND `available`=1 ORDER BY `action_time` DESC";
        $recent0 = $uddb->getResults($sql, [':user' => $this->userId]);

        //滤重
        $ids = $recent = [];
        foreach ($recent0 as $r) {
            if (in_array($r->id, $ids, true)) {
                continue;
            }
            $recent[] = $r;
        }
        
        $taskList = array();
        $recentCount = count($recent); //recent表已完成任务数
        if ($recentCount >= $queryArgs['offset']) { //需要从recent表里取数据
            $recent = array_slice($recent, $queryArgs['offset'], $queryArgs['count']);
            foreach ($recent as $task) {
                $taskList[] = [
                    'date'       => date('Y-m-d', strtotime($task->action_time)),
                    'task_id'    => intval($task->id),
                    'type'       => $taskTypeData[$task->mission_type]->type_name,
                    'title'      => $task->mission_title,
                    'content_id' => intval($task->mission_content_id),
                    'content'    => $task->mission_content,
                    'subtitle'   => '',
                    'done'       => true
                ];
            }

            //计算需要从history表读取的记录数量
            $historyCount = $queryArgs['count'] - count($taskList);
            if ($historyCount > 0) { //需要在history表里取数据,从最新的记录开始连续取
                $sql = "SELECT * FROM `dp_history_mission_action` WHERE `{$this->userIdField}`=:user ORDER BY `action_time` DESC LIMIT 0, {$historyCount}";
                $history = $uddb->getResults($sql, [':user' => $this->userId]);
                
                //有历史记录
                if (!empty($history)) {
                    $taskIds = [];
                    foreach ($history as $task) {

                        if (in_array($task->mission_id, $taskIds, true)) {
                            continue;
                        }

                        $taskList[] = [
                            'date'       => date('Y-m-d', strtotime($task->action_time)),
                            'task_id'    => intval($task->mission_id),
                            'type'       => $taskTypeData[$task->mission_type]->type_name,
                            'content_id' => intval($task->mission_content_id),
                            'content'    => $task->mission_content,
                            'title'      => $task->mission_title,
                            'subtitle'   => '',
                            'done'       => true
                        ];

                        $taskIds[] = $task->mission_id;
                    }
                }
            }

        } else { //无需从recent表里取数据,需要计算在history表里的起始位置
            $historyOffset = $queryArgs['offset'] - $recentCount;
            $sql = "SELECT * FROM `dp_history_mission_action` WHERE `{$this->userIdField}`=:user ORDER BY `action_time` DESC LIMIT {$historyOffset}, {$queryArgs['count']}";
            $history = $uddb->getResults($sql, [':user' => $this->userId]);
            
            //有历史记录
            if (!empty($history)) {
                $taskIds = [];
                foreach ($history as $task) {

                    if (in_array($task->mission_id, $taskIds, true)) {
                        continue;
                    }

                    $taskList[] = [
                        'date'       => date('Y-m-d', strtotime($task->action_time)),
                        'task_id'    => intval($task->mission_id),
                        'type'       => $taskTypeData[$task->mission_type]->type_name,
                        'content_id' => intval($task->mission_content_id),
                        'content'    => $task->mission_content,
                        'title'      => $task->mission_title,
                        'subtitle'   => '',
                        'done'       => true
                    ];

                    $taskIds[] = $task->mission_id;
                }
            }
        }

        return genOutput(1, ['task_list' => $taskList]);
    }
}